/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hu.szitar.forum.server;

import hu.szitar.forum.common.model.User;
import hu.szitar.forum.common.model.UserType;
import hu.szitar.forum.server.dao.UserDAO;
import hu.szitar.forum.server.dao.UserTypeDAO;
import hu.szitar.forum.server.query.HqlType;
import hu.szitar.forum.server.query.QueryParameter;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author tircsil
 */
public class HibernateTest {

    public static void main(String[] args) {
        /*User u = new User();
        u.setUserName("arbuckle");
        u.setPassword("jelszó");

        createUser(u);

        executeHQLQuery("SELECT u FROM User u");*/
        
        List<User> users = UserDAO.getInstance().find("SELECT u FROM User u WHERE u.userName = ?", new QueryParameter<String>(HqlType.TEXT, "arbuckle"));
        
        //List<User> users = UserDAO.getInstance().findAll();
        List<UserType> usertypes = UserTypeDAO.getInstance().findAll();
        System.out.println("users");
        displayResult(users);
        System.out.println("user types");
        displayResult(usertypes);
    }

    private static void executeHQLQuery(String hql) {
        try {
            Session session = HibernateUtil.getSessionFactory().openSession();
            session.beginTransaction();
            Query q = session.createQuery(hql);
            List resultList = q.list();
            displayResult(resultList);
            session.getTransaction().commit();
        } catch (HibernateException he) {
            he.printStackTrace();
        }


    }

    private static void displayResult(List result) {
        for (Object o : result) {
            System.out.println(o);
        }
    }

    private static void createUser(User user) {
        Transaction tx = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            tx = session.beginTransaction();
            session.save(user);
            tx.commit();
        } catch (RuntimeException e) {
            if (tx != null && tx.isActive()) {
                try {
// Second try catch as the rollback could fail as well
                    tx.rollback();
                } catch (HibernateException e1) {
                    e1.printStackTrace();
                }
// throw again the first exception
                throw e;
            }
        }
    }
}
